//
//  CASignUntitledViewController.m
//  CASignUntitled
//
//  Created by  史正烨 on 10-9-25.
//  Copyright __MyCompanyName__ 2010. All rights reserved.
//

#import "CASignUntitledViewController.h"
#import "FileListViewController.h"
#import "EditFormController.h"
#import <QuartzCore/CALayer.h>

@implementation SignedView


- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // Initialization code
		self.multipleTouchEnabled = YES;
		pointsList = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    // Drawing code
	CGContextRef context = UIGraphicsGetCurrentContext();
	
	CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
	CGContextFillRect(context, rect);
	CGContextStrokePath(context);
	
	NSData *colorData= [[NSUserDefaults standardUserDefaults] objectForKey:@"SwatchColor"];
	UIColor *color=nil;
	if (colorData!=nil) {
		color = (UIColor*)[NSKeyedUnarchiver unarchiveObjectWithData:colorData];
	} else {
		color = [UIColor blackColor];
	}
	
	CGContextSetStrokeColorWithColor(context, color.CGColor);
	
	NSNumber *lineWidthData= (NSNumber*)[[NSUserDefaults standardUserDefaults] objectForKey:@"SignedLineWidth"];
	if (lineWidthData!=nil) {
		CGContextSetLineWidth(context, [lineWidthData floatValue]);
	} else {
		CGContextSetLineWidth(context, 3.5);
	}
	
	
	for (NSMutableArray *array in pointsList) {
		int nCount = 0;
		for (NSData *data in array) {
			CGPoint* point = (CGPoint*)[data bytes];
			if (nCount == 0) {
				CGContextMoveToPoint(context, point->x, point->y);
			} else {
				CGContextAddLineToPoint(context, point->x, point->y);
			}
			nCount++;
		}
	}
	
	CGContextStrokePath(context);
}

- (void)dealloc {
	[points release];
	[pointsList release];
    [super dealloc];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	NSLog(@"touchesBegan");
	UITouch* touch = [touches anyObject];
	CGPoint point = [touch locationInView:self];
	
	points = [[NSMutableArray alloc] init];
	[points addObject:[NSData dataWithBytes:&point length:sizeof(CGPoint)]];
	[pointsList addObject:points];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
	NSLog(@"touchesMoved");
	
	UITouch* touch = [touches anyObject];
	CGPoint point = [touch locationInView:self];
	
	[points addObject:[NSData dataWithBytes:&point length:sizeof(CGPoint)]];
	[self setNeedsDisplay];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
	NSLog(@"touchesEnded");
	
	UITouch* touch = [touches anyObject];
	CGPoint point = [touch locationInView:self];
	
	[points addObject:[NSData dataWithBytes:&point length:sizeof(CGPoint)]];
	[points release], points = nil;
	
	[self setNeedsDisplay];
}

- (void)cleanAll
{
	[pointsList removeAllObjects];
	[self setNeedsDisplay];
}

@end


@implementation CASignUntitledViewController
@synthesize isMultiFile;
- (int)identiferId {
	return 0;
}

void ProviderReleaseData (void *info, const void *data, size_t size)
{
    free((void*)data);
}

- (UIImage*) imageBlackToTransparent:(UIImage*) image
{    
    // 分配内存
    const int imageWidth = image.size.width;
    const int imageHeight = image.size.height;    
    size_t      bytesPerRow = imageWidth * 4;
    uint32_t* rgbImageBuf = (uint32_t*)malloc(bytesPerRow * imageHeight);
    
    // 创建context
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpace,
                                                 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
    CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image.CGImage);
    
    // 遍历像素
    int pixelNum = imageWidth * imageHeight;
    uint32_t* pCurPtr = rgbImageBuf;
    for (int i = 0; i < pixelNum; i++, pCurPtr++)
    {
        if ((*pCurPtr & 0xFFFFFF00) == 0xFFFFFF00)    // 将白色变成透明
        {
            uint8_t* ptr = (uint8_t*)pCurPtr;
            ptr[0] = 0;
        }
		
        // 改成下面的代码，会将图片转成灰度
        /*uint8_t* ptr = (uint8_t*)pCurPtr;
		 // gray = red * 0.11 + green * 0.59 + blue * 0.30
		 uint8_t gray = ptr[3] * 0.11 + ptr[2] * 0.59 + ptr[1] * 0.30;    
		 ptr[3] = gray;
		 ptr[2] = gray;
		 ptr[1] = gray;*/
    }
	
	// 将内存转成image
    CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, ProviderReleaseData);
    CGImageRef imageRef = CGImageCreate(imageWidth, imageHeight, 8, 32, bytesPerRow, colorSpace,
										kCGImageAlphaLast | kCGBitmapByteOrder32Little, dataProvider,
                                        NULL, true, kCGRenderingIntentDefault);
    CGDataProviderRelease(dataProvider);
	
    UIImage* resultUIImage = [UIImage imageWithCGImage:imageRef];

    // 释放
    CGImageRelease(imageRef);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    // free(rgbImageBuf) 创建dataProvider时已提供释放函数，这里不用free
    
    return resultUIImage;
}

- (void)saveScreen:(UIView*)view
{
	UIGraphicsBeginImageContext(view.frame.size);
	[view.layer renderInContext:UIGraphicsGetCurrentContext()];
	UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
/*	
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *filePath = [documentsDirectory stringByDeletingLastPathComponent];
	//filePath = [filePath stringByAppendingPathComponent:@"Default.png"];
	filePath = @"Users/shizhengye/Desktop/view.png";
	
	NSError *error;
	if([UIImagePNGRepresentation([self imageBlackToTransparent:image]) writeToFile:filePath options:NSAtomicWrite error:&error]) {
		NSLog(@"%@ save ok!", filePath);
	} else {
		NSLog(@"%@ save failed, error:%@", filePath, [error description]);
	}
*/
	NSCalendar* calendar = [NSCalendar currentCalendar];
	NSUInteger unFlag = NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit |
	NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit |
	NSSecondCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit;
	NSDateComponents *comps = [calendar components:unFlag fromDate:[NSDate date]];
	
	NSString *fileName= (NSString*)[[NSUserDefaults standardUserDefaults] objectForKey:@"SignedFileName"];
	if (fileName == nil) {
		fileName = [NSString stringWithFormat:@"signedFile%d%02d%02d%02d%02d%02d.png", 
					comps.year, comps.month, comps.day, comps.hour, comps.minute, comps.second];
	}
	
	NSString *fullfileName = [NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), fileName ];
	NSData* fileData = UIImagePNGRepresentation([self imageBlackToTransparent:image]);
	
		
	if (isMultiFile) {
		FileListViewController *fileListView = [self.navigationController.viewControllers objectAtIndex:[self.navigationController.viewControllers count] - 2];
		[fileListView getUploadFileName];
		fileListView.cacheFile = fileName;
		fileListView.fileData = [NSInputStream inputStreamWithData:fileData];
	}else {
		EditFormController *editFormController = [self.navigationController.viewControllers objectAtIndex:[self.navigationController.viewControllers count] - 2];
		[editFormController getUploadFileName];
		editFormController.cacheFile = fileName;
		editFormController.fileData = [NSInputStream inputStreamWithData:fileData];
	}
	
	//保存到本地临时文件夹下
	NSError *error;
	NSFileManager *fileManager = [NSFileManager defaultManager];
	[fileManager changeCurrentDirectoryPath:[NSTemporaryDirectory() stringByExpandingTildeInPath]];
	[fileManager createFileAtPath:fullfileName contents:nil attributes:nil];
	if([fileData writeToFile:fullfileName options:NSAtomicWrite error:&error]) {
		NSLog(@"%@ save ok!", fullfileName);
	} else {
		NSLog(@"%@ save failed, error:%@", fullfileName, [error description]);
	}
	
	[self.navigationController popViewControllerAnimated:YES];
}

- (id)init {
	if (self = [super init]) {
		self.hidesBottomBarWhenPushed = YES;
	}
	return self;
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	self.title = @"手写签名";
	[self rightBarButton:@"上传" withStyle:UIBarButtonItemStyleDone selector:@selector(sendAction:)];
	
	UIToolbar *toolBar = [UIToolbar new];
	toolBar.barStyle = UIBarStyleDefault;
	[toolBar sizeToFit];

	toolBar.tintColor = self.userDefaults.skin_navigationBarColor;
	toolBar.frame = CGRectMake(0.0, self.height-nToolBarHeight, self.width, nToolBarHeight);
	toolBar.autoresizingMask = nMCViewAutoresizingMask;
	toolBar.tag = -1;
	UIBarButtonItem *signedSetting = [[UIBarButtonItem alloc] initWithTitle:@"签名设置" style:UIBarButtonItemStyleBordered target:self action:@selector(signedSetting:)];
	UIBarButtonItem *cleanScreen = [[UIBarButtonItem alloc] initWithTitle:@"清除屏幕" style:UIBarButtonItemStyleBordered target:self action:@selector(cleanScreen:)];	
	UIBarButtonItem *flexItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
	NSArray *items = [NSArray arrayWithObjects: signedSetting, flexItem, cleanScreen, nil];	
	
	[signedSetting release];
	[cleanScreen release];
	[flexItem release];
	
	[toolBar setItems:items animated:NO];
	[self.clientView addSubview:toolBar];
	
	signedView = [[SignedView alloc] initWithFrame:CGRectMake(0, 0, self.width, toolBar.frame.origin.y)];
	signedView.autoresizingMask = nMCViewAutoresizingMask;
	[self.clientView addSubview:signedView];
	
	[toolBar release];
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	
	[self.clientView viewWithTag:-1].frame = CGRectMake(0.0, self.height-nToolBarHeight, self.width, nToolBarHeight);
	signedView.frame = CGRectMake(0, 0, self.width, self.height-nToolBarHeight);
}


// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return NO;
}


- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[signedView release];
    [super dealloc];
}

-(void)sendAction:(id)sender
{
	[self saveScreen:signedView];
}

#pragma mark ---UIToolbar事件---
-(void)signedSetting:(id)inSender {
	SignedSettingController* controller = [[SignedSettingController alloc] init];
	[self.navigationController pushViewController:controller animated:YES];
	[controller release];
}

-(void)cleanScreen:(id)inSender {
	[signedView cleanAll];
}

@end


@implementation SignedSettingController
- (int)identiferId {
	return 0;
}
- (id)init {
	if (self = [super init]) {
		self.hidesBottomBarWhenPushed = YES;
	}
	return self;
}
- (void)viewDidLoad {
	
	[super viewDidLoad];
	
	self.title = @"签名设置";
	[self rightBarButton:@"确定" withStyle:UIBarButtonItemStyleDone selector:@selector(confirmAction:)];
	
	self.tableview.backgroundColor = [UIColor clearColor];
	
	lineWidthPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, self.height, self.width, nPickerHeight)];
	lineWidthPicker.showsSelectionIndicator = YES;
	lineWidthPicker.dataSource = self;
	lineWidthPicker.delegate = self;
	[self.clientView addSubview:lineWidthPicker];
}

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	
	lineWidthPicker.frame = CGRectMake(0, self.height, self.width, nPickerHeight);
}

- (void)dealloc {
	[lineWidthPicker release];
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return NO;
}

-(void)confirmAction:(id)sender
{
	UITableViewCell* cell = [tableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
	UIView* colorSwatch = (UIView*)[cell viewWithTag:-1];
	NSData *colorData = [NSKeyedArchiver archivedDataWithRootObject:colorSwatch.backgroundColor];
    [[NSUserDefaults standardUserDefaults] setObject:colorData forKey:@"SwatchColor"];
	
	cell = [tableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
	UILabel* lineWidthDisplay = (UILabel*)[cell viewWithTag:-1];
	[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithFloat:[lineWidthDisplay.text floatValue]] forKey:@"SignedLineWidth"];
	
	cell = [tableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
	UITextField* fileNameField = (UITextField*)[cell viewWithTag:-1];
	NSString* fileName = [NSString stringWithFormat:@"%@.png", fileNameField.text];
	if (![fileName isEqualToString:@".png"]) {
		[[NSUserDefaults standardUserDefaults] setObject:fileName forKey:@"SignedFileName"];
	}
	
	[self.navigationController popViewControllerAnimated:YES];
}

#pragma mark ---- UITableView方法 ----

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	UITableViewCell *cell;
	static NSString *cellIdentifier_Style1 = @"cellIdentifier_Style1";
	cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier_Style1];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier_Style1] autorelease];
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		cell.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.7];
		if (indexPath.row == 0) {
			UIView*  colorShow = [[UIView alloc] initWithFrame:CGRectMake(self.width-70, 5, 35, 35)];
			colorShow.tag = -1;
			NSUserDefaults *saveColors = [NSUserDefaults standardUserDefaults];
			NSData *colorData= [saveColors objectForKey:@"SwatchColor"];
			UIColor *color=nil;
			if (colorData!=nil) {
				color = (UIColor*)[NSKeyedUnarchiver unarchiveObjectWithData:colorData];
			} else {
				color = [UIColor blackColor];
			}
			colorShow.backgroundColor = color;
			[cell addSubview:colorShow];
			[colorShow release];
		} else if (indexPath.row == 1) {
			UILabel *lbValue = [[UILabel alloc] initWithFrame:CGRectMake(self.width-110, 10, 75, 25)];
			lbValue.textColor = [UIColor colorWithRed:0.282 green:0.341 blue:0.455 alpha:1];
			lbValue.backgroundColor = [UIColor clearColor];
			[cell addSubview:lbValue];
			lbValue.tag = -1;
			
			NSUserDefaults *saveLineWidth = [NSUserDefaults standardUserDefaults];
			NSNumber *lineWidthData= (NSNumber*)[saveLineWidth objectForKey:@"SignedLineWidth"];
			if (lineWidthData!=nil) {
				lineWidth = [lineWidthData floatValue];
			} else {
				lineWidth = 3.5;
			}
			lbValue.text = [NSString stringWithFormat:@"%.1f像素宽", lineWidth];
			[lbValue release];
		} else {
			cell.accessoryType = UITableViewCellAccessoryNone;
			NSString *filename= (NSString*)[[NSUserDefaults standardUserDefaults] objectForKey:@"SignedFileName"];
			UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(self.width-200, 10, 180, 25)];
			field.clearsOnBeginEditing = NO;
			field.keyboardType = UIKeyboardTypeDefault;
			field.returnKeyType = UIReturnKeyDone;
			field.textAlignment = UITextAlignmentRight;
			field.tag = -1;
			field.text = filename==nil?@"":[filename stringByDeletingPathExtension];
			field.textColor = [UIColor colorWithRed:0.282 green:0.341 blue:0.455 alpha:1];
			[field addTarget:self action:@selector(textFieldDone:) forControlEvents:UIControlEventEditingDidEndOnExit];
			[cell addSubview:field];
			[field release];
		}
	} 
	cell.textLabel.backgroundColor = [UIColor clearColor];
	if (indexPath.row == 0) {
		cell.textLabel.text = @"颜色设定";
	} else if (indexPath.row == 1) {
		cell.textLabel.text = @"线宽设定";
	} else {
		cell.textLabel.text = @"文件名设定";
	}
		
	
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	if (indexPath.row == 0) {
		ColorPickerViewController* controller = [[ColorPickerViewController alloc] initWithNibName:@"ColorPickerViewController" bundle:nil];
		
		controller.delegate = self;
		controller.defaultsKey = @"SwatchColor";
		[self presentModalViewController:controller animated:YES];
		[controller release];
	} else if (indexPath.row == 1) {
		if (CGRectGetMinY(lineWidthPicker.frame)==self.height) {
			NSUserDefaults *saveLineWidth = [NSUserDefaults standardUserDefaults];
			NSNumber *lineWidthData= (NSNumber*)[saveLineWidth objectForKey:@"SignedLineWidth"];
			int nSelectedRow = [lineWidthData floatValue]/0.5-1;
			
			[lineWidthPicker selectRow:nSelectedRow<0?0:nSelectedRow inComponent:0 animated:NO];
			
			CGRect originFrame = lineWidthPicker.frame;
			CGRect finalFrame = CGRectMake(originFrame.origin.x, 
										   CGRectGetMinY(originFrame)-originFrame.size.height, 
										   originFrame.size.width, 
										   originFrame.size.height);
			
			[UIView beginAnimations:nil context:NULL];
			[UIView setAnimationDuration:0.3];
			lineWidthPicker.frame = finalFrame;
			[UIView commitAnimations];
		} else {
			CGRect originFrame = lineWidthPicker.frame;
			CGRect finalFrame = CGRectMake(originFrame.origin.x, 
										   CGRectGetMinY(originFrame)+originFrame.size.height, 
										   originFrame.size.width, 
										   originFrame.size.height);
			
			[UIView beginAnimations:nil context:NULL];
			[UIView setAnimationDuration:0.3];
			lineWidthPicker.frame = finalFrame;
			[UIView commitAnimations];
		}
	}
}

- (void)colorPickerViewController:(ColorPickerViewController *)colorPicker didSelectColor:(UIColor *)color {
    
    //NSData *colorData = [NSKeyedArchiver archivedDataWithRootObject:color];
    //[[NSUserDefaults standardUserDefaults] setObject:colorData forKey:colorPicker.defaultsKey];
    
    if ([colorPicker.defaultsKey isEqualToString:@"SwatchColor"]) {
        //colorSwatch.backgroundColor = color;
		UITableViewCell* cell = [tableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
		UIView* colorSwatch = (UIView*)[cell viewWithTag:-1];
		colorSwatch.backgroundColor = color;
    }
	
    [colorPicker dismissModalViewControllerAnimated:YES];
}

- (IBAction) textFieldDone:(id)sender
{
	[sender resignFirstResponder];
}

#pragma mark -- UIPickerView --
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return 1;
}
// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	return 12;
}
/*
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
	return [NSString stringWithFormat:@"%.1f像素宽", (row+1)*0.5];
}
*/
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
	CGRect rc = CGRectMake(7, 0, 292, 50);
	
	UIView *retView = [[UIView alloc] initWithFrame:rc];
	retView.backgroundColor = [UIColor clearColor];
	UILabel *lable = [[UILabel alloc] initWithFrame:rc];
	lable.backgroundColor = [UIColor clearColor];
	lable.text = [NSString stringWithFormat:@"%.1f像素宽", (row+1)*0.5];
	
	lable.textAlignment = UITextAlignmentCenter;
	[retView addSubview:lable];
	[lable release];
	
	return retView;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	UITableViewCell* cell = [tableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
	UILabel* lineWidthDisplay = (UILabel*)[cell viewWithTag:-1];
	lineWidthDisplay.text = [NSString stringWithFormat:@"%.1f像素宽", (row+1)*0.5];
	
	CGRect originFrame = pickerView.frame;
	CGRect finalFrame = CGRectMake(originFrame.origin.x, 
								   CGRectGetMinY(originFrame)+originFrame.size.height, 
								   originFrame.size.width, 
								   originFrame.size.height);
	
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.3];
	pickerView.frame = finalFrame;
	[UIView commitAnimations];
}
@end
